package com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest;

import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;

import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.ImageLoader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.nio.ByteBuffer;

/**
 * @description SD卡缓存，缓存的不是真实的图片，而是编码后的文件
 * @vresion 1.0
 * Created by 安帅 on 2015/10/8 16:06.
 */
public class DiskBitmapCache extends DiskBasedCache implements ImageLoader.ImageCache {
    public DiskBitmapCache(File rootDirectory, int maxCacheSizeInBytes) {
        super(rootDirectory, maxCacheSizeInBytes);
    }

    public DiskBitmapCache(File cacheDir) {
        super(cacheDir);
    }

    @Override
    public Bitmap getBitmap(String url) {
        final Entry requestedItem = get(url);

        if (requestedItem == null)
            return null;

        return BitmapFactory.decodeByteArray(requestedItem.data, 0,
                requestedItem.data.length);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        final Entry entry = new Entry();
        entry.data = convertBitmapToBytes(bitmap);
        put(url, entry);
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public static byte[] convertBitmapToBytes(Bitmap bitmap) {
        ByteBuffer buffer = ByteBuffer.allocate(bitmap.getByteCount());
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {

                bitmap.copyPixelsToBuffer(buffer);

                return buffer.array();

            } else {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte[] data = baos.toByteArray();
                return data;
            }
        } catch (OutOfMemoryError e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
            //bitmap.recycle();
            System.gc();
            return null;
        } finally {
            closeInputStream(buffer);

        }
    }

    private static void closeInputStream(ByteBuffer buffer) {
        if (null != buffer) {
            buffer.clear();
        }
    }
}
